package com.example.doubledatasource.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.doubledatasource.common.BusinessException;
import com.example.doubledatasource.common.PageResult;
import com.example.doubledatasource.common.Result;
import com.example.doubledatasource.converter.UserConverter;
import com.example.doubledatasource.dto.UserDTO;
import com.example.doubledatasource.entity.User;
import com.example.doubledatasource.query.UserQuery;
import com.example.doubledatasource.service.UserService;
import com.example.doubledatasource.vo.UserVO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * 
 * @author example
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserConverter userConverter;

    /**
     * 分页查询用户
     * 支持多条件查询和排序
     */
    @GetMapping
    public PageResult<UserVO> getUsersByPage(UserQuery query) {
        // 调用Service进行分页查询
        IPage<User> userPageResult = userService.findUsersByQuery(query);

        // 使用IPage和转换器创建PageResult
        return PageResult.success(userPageResult, userConverter::toVOList);
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public Result<UserVO> getUserById(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        UserVO userVO = userConverter.toVO(user);
        return Result.success(userVO);
    }

    /**
     * 根据用户名查询用户
     */
    @GetMapping("/username/{username}")
    public Result<UserVO> getUserByUsername(@PathVariable("username") String username) {
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        UserVO userVO = userConverter.toVO(user);
        return Result.success(userVO);
    }

    /**
     * 获取活跃用户（分页）
     */
    @GetMapping("/active")
    public PageResult<UserVO> getActiveUsers(UserQuery query) {
        // 这里可以添加活跃用户的特定查询条件
        // 例如：最近登录时间、活跃度等

        // 调用Service进行分页查询
        IPage<User> userPageResult = userService.findUsersByQuery(query);

        // 使用IPage和转换器创建PageResult
        return PageResult.success(userPageResult, userConverter::toVOList);
    }

    /**
     * 创建用户
     */
    @PostMapping
    public Result<UserVO> createUser(@Valid @RequestBody UserDTO userDTO) {
        User user = userConverter.toEntity(userDTO);
        userService.save(user);
        UserVO userVO = userConverter.toVO(user);
        return Result.success("用户创建成功", userVO);
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Result<UserVO> updateUser(@PathVariable("id") Long id, @Valid @RequestBody UserDTO userDTO) {
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        userConverter.updateEntity(user, userDTO);
        userService.updateById(user);
        UserVO userVO = userConverter.toVO(user);
        return Result.success("用户更新成功", userVO);
    }



    /**
     * 根据关键字搜索用户（分页）
     */
    @GetMapping("/search")
    public PageResult<UserVO> searchUsers(@RequestParam("keyword") String keyword, UserQuery query) {
        // 设置查询条件
        query.setKeyword(keyword);

        // 调用Service进行分页查询
        IPage<User> userPageResult = userService.findUsersByQuery(query);

        // 使用IPage和转换器创建PageResult
        return PageResult.success(userPageResult, userConverter::toVOList);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable("id") Long id) {
        boolean removed = userService.removeById(id);
        if (!removed) {
            throw new BusinessException("用户删除失败");
        }
        return Result.success("用户删除成功", null);
    }
}
